package com.yunyao.web.controller.init;

import com.yunyao.common.constant.CacheConstants;
import com.yunyao.common.core.redis.RedisCache;
import com.yunyao.common.dto.dict.DataDictionary;
import com.yunyao.common.web.util.EnumUtils;
import com.yunyao.common.web.util.YResult;
import com.yunyao.web.utils.DictUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Class：RedisInitController
 * @Description： 初始化redis
 * @Author：chenyejian
 * @Date：Created in 2024/07/15 8:46
 */
@RestController
@RequestMapping("/cache")
@Slf4j
public class RedisInitController implements InitializingBean, CommandLineRunner {
    private static final String scanPackage = "com.yunyao.common.constant.enums";
    private static final String REDIS_KEY = CacheConstants.STATUS_CACHE;
    private static final String DICT_KEY = CacheConstants.DICT_KEY;
    @Autowired
    private RedisCache redisCache;

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    /**
     * 根据字典code或者状态常量获取数据
     *
     * @param
     * @return 查询数据
     */
    @GetMapping(value = "/redis/query")
    public YResult<Map<String, String>> queryRedis(String key) {
        if (key == null || key.equals("")) {
            return YResult.error("key不能为空");
        }
        //处理key，转为大写，并去除下划线
        String redisKey = key.replace("_", "").toUpperCase();
        if (redisCache.hasKey(REDIS_KEY + redisKey)) {
            //获取redis中的枚举类数据
            Map enumMap = redisCache.getEnumMap(REDIS_KEY + redisKey);
            if (null != enumMap && enumMap.size() > 0) {
                return YResult.success(enumMap);
            }
        }
        if (redisCache.hasKey(DICT_KEY + redisKey)) {
            //获取redis中的字典数据
            List<DataDictionary> dataDictionaryList = redisCache.getCacheList(DICT_KEY + redisKey
                    , DataDictionary.class);
            /**
             * dataDictionaryList 转成 LinkedHashMap<String,Stirng>
             */
            Map<String, String> map = new LinkedHashMap<>();
            for (DataDictionary dataDictionary : dataDictionaryList) {
                map.put(dataDictionary.getKey(), dataDictionary.getValue());
            }
            return YResult.success(map);
        }
        if (DictUtils.getDictList(key) != null && DictUtils.getDictList(key).size() > 0) {
            //获取redis中的字典数据,不成功，从数据库中读取，并写入缓存中
            List<DataDictionary> dataDictionaryList = DictUtils.getDictList(key);
            /**
             * dataDictionaryList 转成 LinkedHashMap<String,Stirng>
             */
            Map<String, String> map = new LinkedHashMap<>();
            dataDictionaryList.forEach(dataDictionary -> {
                map.put(dataDictionary.getKey(), dataDictionary.getValue());
            });
            return YResult.success(map);
        }
        try {
            Map<String, String> enumMap =
                    EnumUtils.generateKeyValueMap(scanPackage + "." + Character.toUpperCase(key.charAt(0)) + key.substring(1));
            redisCache.setEnumMap2Hash(REDIS_KEY + redisKey, enumMap);
            //获取枚举类中的数据
            return YResult.success(enumMap);
        } catch (Exception e) {
            log.error("没有数据", e);
        }
        return YResult.error("没有数据");
    }

    /**
     * 根据字典code或者状态常量获取数据
     *
     * @param
     * @return 查询数据
     */
    @GetMapping(value = "/redis/queryDict")
    public YResult<List<DataDictionary>> queryRedisDict(String key) {
        if (key == null || key.equals("")) {
            return YResult.error("key不能为空");
        }
        //处理key，转为大写，并去除下划线
        String redisKey = key.replace("_", "").toUpperCase();
        if (redisCache.hasKey(DICT_KEY + redisKey)) {
            //获取redis中的字典数据
            List<DataDictionary> dataDictionaryList = redisCache.getCacheList(DICT_KEY + redisKey
                    , DataDictionary.class);
            /**
             * dataDictionaryList 转成 LinkedHashMap<String,Stirng>
             */
            return YResult.success(dataDictionaryList);
        }
        if (DictUtils.getDictList(key) != null) {
            //获取redis中的字典数据,不成功，从数据库中读取，并写入缓存中
            List<DataDictionary> dataDictionaryList = DictUtils.getDictList(key);
            return YResult.success(dataDictionaryList);
        }
        return YResult.error("没有数据");
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("初始化redis字典数据");
        DictUtils.initAllDictionaryListCache();
    }
}
